package com.hsnn.medstgmini.common.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.hsnn.medstgmini.common.model.StdAttachment;
import com.hsnn.medstgmini.common.service.AttachmentPlug;
import com.hsnn.medstgmini.util.ParseDate;

@Service
public class AttachmentPlugImpl implements AttachmentPlug {
	
	@Value("${system.uploadPath}")
	private String uploadPath;
	
	@Value("${system.sysId}")
	private String sysId;
	
	
	public String processAttachment(MultipartFile[] files){
		if(files==null){
			return "";
		}
		List<StdAttachment> attas = new ArrayList<StdAttachment>();
        for (MultipartFile mf : files) {
				//文件相关信息
				String filename = mf.getOriginalFilename(); // 文件名称
				String suffix = filename.substring(filename.lastIndexOf(".")).toLowerCase(); // 文件后缀
				filename = UUID.randomUUID().toString() + suffix;
				
				String dirPath = ParseDate.parseShortFormat(new Date()).replaceAll("-", "/"); // 年月路径
				String filePath = uploadPath + dirPath + "/" + filename;
				
				File destFile = new File(filePath);
				try {
					FileUtils.copyInputStreamToFile(mf.getInputStream(), destFile);
				} catch (IOException e) {
					e.printStackTrace();
			    }
				StdAttachment item = new StdAttachment();
				item.setUrl("/attachment/download.html?fileName="+ filename +"&path=" +  filePath);
				attas.add(item);
		 }
        return JSON.toJSONString(attas);
	}
	
	
}
